package kr.hkit.androidcomplete03.ch25;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

public class WordDAO {
	private WordDBHelper helper;
	private SQLiteDatabase db;
	

	public WordDAO(Context context) {
		helper = new WordDBHelper(context);
		db = helper.getWritableDatabase();
	}
	
	public static WordDAO open(Context context){
		return new WordDAO(context);
	}
	
	public void close(){
		helper.close();
	}
	
	
	public boolean insert(String eng, String han){
		/*String sql = "insert into dic values(null, '"+eng+"','"+han+"');";
		try{
			db.execSQL(sql);
		}catch(SQLException e){
			Log.d("WordDAO", "insert Error" + e.getMessage());
			return false;
		}
		return true;*/
		
		ContentValues row = new ContentValues();
		row.put("eng", eng);
		row.put("han", han);
		long res = db.insert("dic", null, row);
		if(res == -1) return false;
		return true;
	}
	
	public boolean deleteAll(){
		/*String sql = "delete from dic;";
		try{
			db.execSQL(sql);
		}catch(SQLException e){
			Log.d("WordDAO", "deleteAll Error" + e.getMessage());
			return false;
		}
		return true;*/
		
		db.delete("dic", null, null);
		return true;
	}
	
	public boolean delete(int id){
/*		String sql = "delete from dic where _id="+id+";";
		try{
			db.execSQL(sql);
		}catch(SQLException e){
			Log.d("WordDAO", "delete Error " + e.getMessage());
			return false;
		}
		return true;*/
		String[] args = {String.valueOf(id)};
		db.delete("dic", "_id=?", args);
		return true;
	}
	
	public Cursor selectAll(){
		String sql ="select * from dic;";
		Cursor cursor = db.rawQuery(sql, null);
		if(cursor != null) cursor.moveToFirst();
		return cursor;
	}
	
	public boolean update(int id, String eng, String han){
		String sql ="update dic set han ='"+han+"', eng ='"+eng+"' where _id ="+id+";";
		try{
			db.execSQL(sql);
		}catch(SQLException e){
			Log.d("WordDAO", "update Error" + e.getMessage());
			return false;
		}
		return true;
	}
}
